package repositories

import (
	"context"
	"errors"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"nodeseller/datamodels"
	mymongo "nodeseller/mongo"
)
//User表的操作
type IUser interface {
	//连接数据库
	Conn()(error)
	//插入数据库
	Insert(user *datamodels.User)(error)
	//删除数据库
	Delete(primitive.ObjectID)bool
	//修改余额
	Update(phonenumber string,paycash float32)error
	//登陆
	Login(phonenumber string,password string)error
	//查账户详情
	SelectByKey(string)(*datamodels.UserInfo,error)
}

type UserManager struct {
	mongoDataColletion mymongo.Collection
}

func NewUser()IUser  {
	mongodb,err := mymongo.Get()
	if err != nil{
		return nil
	}
	return &UserManager{
		mongodb.Collection("user"),
	}
}
//数据库连接
func (p *UserManager)Conn()(err error)  {
	if p.mongoDataColletion == nil{
		mongodb,err := mymongo.Get()
		if err != nil{
			return err
		}
		p.mongoDataColletion = mongodb.Collection("user")
	}
	return nil
}
//注册账号
func (p *UserManager)Insert(user *datamodels.User)(error)  {
	//判断连接是否存在
	if err := p.Conn();err != nil{
		return  err
	}
	var resultdata datamodels.User
	p.mongoDataColletion.FindOne(context.TODO(),bson.M{"phonenumber":user.PhoneNumber}).Decode(&resultdata)
	if resultdata.PhoneNumber == ""{
		//插入
		_,err := p.mongoDataColletion.InsertOne(context.TODO(),*user)
		if err != nil{
			return  err
		}
		return nil
	}
	return errors.New("账号已注册")

}
//登陆
func (p *UserManager)Login(phonenumber string,password string)error  {
	//判断连接是否存在
	if err := p.Conn();err != nil{
		return errors.New("数据库连接失败")
	}
	var resultdata datamodels.User
	p.mongoDataColletion.FindOne(context.TODO(),bson.M{"phonenumber":phonenumber,"password":password}).Decode(&resultdata)
	if resultdata.PhoneNumber != ""{
		return nil
	}
	return errors.New("登陆失败")
}
//注销账号
func (p *UserManager)Delete(userid primitive.ObjectID)bool  {
	//判断连接是否存在
	if err := p.Conn();err != nil{
		return false
	}
	//删除
	deleteresult,err := p.mongoDataColletion.UpdateOne(context.TODO(),bson.M{"_id":userid},bson.D{{"$set",bson.M{"delete":true}}})
	if err != nil{
		return false
	}
	if deleteresult.UpsertedCount > 0{
		return true
	}
	return false
}
//减余额
func (p *UserManager)Update(phonenumber string,paycash float32)(result error)  {
	//判断连接是否存在
	if err := p.Conn();err != nil{
		return
	}
	uploadresult,err := p.mongoDataColletion.UpdateOne(context.TODO(),bson.M{"phonenumber":phonenumber},bson.D{{"$inc",bson.M{"cash":-paycash}}})
	if err != nil{
		return err
	}
	if uploadresult.ModifiedCount >0 {
		return nil
	}
	return errors.New("花费金币失败")
}
//查账户详情
func (p *UserManager)SelectByKey(phonenumber string)(result *datamodels.UserInfo,err error)  {
	//判断连接是否存在
	if err := p.Conn();err != nil{
		return nil,err
	}
	p.mongoDataColletion.FindOne(context.TODO(),bson.M{"phonenumber":phonenumber}).Decode(&result)
	return result,nil
}